package com.inspector.app.ui.widget;

import android.text.InputFilter;
import android.text.Spanned;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Android EditText NumberInputFilter实现整数和小数位数限制
 * https://juejin.cn/post/6844904006418956295
 */
public class NumRangeInputFilter implements InputFilter {
    Pattern mPattern;

    public NumRangeInputFilter(int digitsBeforeZero, int digitsAfterZero) {
        String regex = String.format("[0-9]{0,%d}+(\\.[0-9]{0,%d})?", digitsBeforeZero, digitsAfterZero);
        mPattern = Pattern.compile(regex);
    }

    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
        try {
            //直接输入"."返回"0."
            //".x"删除"x"输出为"."，inputFilter无法处理成"0."，所以只处理直接输入"."的case
            if (".".equals(source) && "".equals(dest.toString())) {
                return "0.";
            }

            String sourceText = source.toString();
            String destText = dest.toString();
            String temp = destText.substring(0, dstart)
                    + sourceText.substring(start, end)
                    + destText.substring(dend, dest.length());
            if (!temp.contains(".")) {
                if (temp.startsWith(".") || temp.startsWith("00")) {
                    return dest.subSequence(dstart, dend);
                }
            }

            StringBuilder builder = new StringBuilder(dest);
            if ("".equals(source)) {
                builder.replace(dstart, dend, "");
            } else {
                builder.insert(dstart, source);
            }
            String resultTemp = builder.toString();
            //判断修改后的数字是否满足小数格式，不满足则返回 "",不允许修改
            Matcher matcher = mPattern.matcher(resultTemp);
            if (!matcher.matches()) {
                return "";
            }
        } catch (Exception e) {

        }
        return null;
    }

}
